package cz.hanis.android.pubaccounting;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import cz.hanis.android.pubaccounting.app.PubAccountingApp;
import cz.hanis.android.pubaccounting.db.DbManager;
import cz.hanis.android.pubaccounting.model.Pub;

public class PubDetailActivity extends Activity{

	public static final String PUB_ID_KEY = "pub_id";
		
	private DbManager dbManager;
	
	private Pub pub;		
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pub_detail);
		
		dbManager = ((PubAccountingApp) getApplication()).getDbManager();
								
		long pubId = getIntent().getLongExtra(PubEditingActivity.PUB_ID_KEY, -1);
		if(pubId != -1) {			
			pub = dbManager.getPub(pubId);
			applyPub(pub);
		}	
	}
	
	private void applyPub(final Pub pub) {

		Button locationButton = (Button) findViewById(R.id.pub_detail_location);
		locationButton.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				showOnMap(pub);
			}
		});
		if(!pub.isLocalizable()) {
			locationButton.setEnabled(false);
		}
		
		Button homepageButton = (Button) findViewById(R.id.pub_detail_homepage);
	    homepageButton.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				goToPubHomepage(pub);
			}
		});
		if(pub.getHompage() == null || "".equals(pub.getHompage())) {
			homepageButton.setEnabled(false);
		}
		
		Button editButton = (Button) findViewById(R.id.pub_detail_edit);
		editButton.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				startEditActivity(pub);
			}
		});
		
		((TextView) findViewById(R.id.pub_detail_name)).setText(pub.getName());
		((TextView) findViewById(R.id.pub_detail_address)).setText(pub.getAddress());
	}
	
	
	private void startEditActivity(Pub pub) {		
		Intent intent = new Intent(this, PubEditingActivity.class);
		intent.putExtra(PubEditingActivity.PUB_ID_KEY, pub.getId());
		startActivity(intent);		
		//super.onListItemClick(l, v, position, id);			
	}
	
	private void goToPubHomepage(Pub pub) {
		Intent intent = new Intent("android.intent.action.VIEW", 
				Uri.parse(pub.getHompage()));
		startActivity(intent); 
	}
		
	private void showOnMap(Pub pub) {
		
		
		Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "608755876"));		
//		String uri = "geo:"+ pub.getLatitude() + "," + pub.getLongitude();
//		Intent intent = new Intent("android.intent.action.VIEW", 
//				Uri.parse(uri));
		startActivity(intent); 
	}	

}
